package org.demo.cnck.controller.api;

import org.apache.commons.lang3.StringUtils;
import org.demo.cnck.controller.error.BussinessException;
import org.demo.cnck.controller.vm.HttpMessage;
import org.demo.cnck.controller.vm.MessageHelper;
import org.demo.cnck.dao.domain.Pet;
import org.demo.cnck.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by cdyoue on 2018/11/20.
 */
@Controller
public class PetController {
    @Autowired
    private PetService petService;

    @GetMapping("pets")
    public ResponseEntity<List<Pet>> listPets(@RequestParam(value = "petname", required = false) String petname, @RequestParam(value = "id", required = false) Long  id) {
        List<Pet> pets = petService.findAll(petname, id);
        return ResponseEntity.ok(pets);
    }


    @PostMapping("pets")
    public ResponseEntity<HttpMessage> addPets(Pet pet) {
        if (StringUtils.isBlank(pet.getPetname())) {
            throw new BussinessException("名称不能为空");
        }

        petService.save(pet);
        return ResponseEntity.ok(MessageHelper.OK().message("新增成功").build());
    }


    @DeleteMapping("pets/{id}")
    public ResponseEntity<HttpMessage> delPets(@PathVariable("id")Long id) {
        petService.del(id);
        return ResponseEntity.ok(MessageHelper.OK().message("删除成功").build());
    }
}
